//
//  CarpoolWithFriendsAdapter.m
//  CarpoolWithFriends
//
//  Created by Yang Lu on 4/27/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "CarpoolWithFriendsAdapter.h"
#import "CarpoolWithFriendsServer.h"
#import "CJSONSerializer.h"
#import "CJSONDeserializer.h"
#import "ConnectionUtility.h"

@implementation CarpoolWithFriendsAdapter

static NSString *REQUEST_FORMAT[] ={@"GET", @"POST", @"PUT", @"DELETE"};


+(NSString*)generalRequest:(enum REQUEST_TYPE)reqType syncMode:(enum SYNC_MODE)syncMode apiName:(NSString*)apiNameStr sendData:(NSObject*)sendData
{
    NSString *custQueryStr = nil;
    NSData *jsonData = nil;
    if(reqType == GET) {
        custQueryStr = (NSString*)sendData;
    }
    else {
        jsonData = (NSData*)sendData;
    }
    
    NSURL *myURL = [CarpoolWithFriendsServer getServerURL:apiNameStr queryString:custQueryStr];
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:myURL];
    
    [request setRequestMethod:REQUEST_FORMAT[reqType]];
    
    if(reqType == POST || reqType == PUT)
    {
        [request addRequestHeader:@"User-Agent" value:@"ASIHTTPRequest"];
        [request addRequestHeader:@"Content-Type" value:@"application/json"];
        //[request appendPostData:[jsonData dataUsingEncoding:NSUTF8StringEncoding]];
        [request appendPostData:jsonData];
    }
    
    if(syncMode == SYNCHRONOUS) {
        [request startSynchronous];
    }
    else {
        [request setCompletionBlock:^{
            // Use when fetching text data
            //NSString *responseString = [request responseString];
            
            // Use when fetching binary data
            //NSData *responseData = [request responseData];
        }];
        [request setFailedBlock:^{
            //NSError *error = [request error];
        }];
        
        [request startAsynchronous];
    }
    
    NSString *response = [request responseString];
    NSError *error = [request error];
    
    if(!error && ([response isEqualToString:@"\"FAILED\""] == NO))
    {
        
        return response;
    }
    else 
    {
        return @"FAILED";
    }
    
}

+(NSString*)formRequest:(enum SYNC_MODE)syncMode apiName:(NSString*)apiNameStr dataPath:(NSString*)dataPath sendData:(NSData*)sendData postData:(NSObject*)postData imageKey:(NSString*)imageKey
{
    
    NSURL *myURL = [CarpoolWithFriendsServer getServerURL:apiNameStr queryString:nil];

    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:myURL];
    
    [request setRequestMethod:@"POST"];
    [request setPostFormat:ASIMultipartFormDataPostFormat];
    
    //NSString *fileName = [NSString stringWithFormat:@"%@.%@",dataName,dataFormat];
    //[request addPostValue:dataPath forKey:@"name"];
    [request setPostValue:postData forKey:@"postData"];
    
    // Upload an image
    NSArray *strArray=[dataPath componentsSeparatedByString:@"."];
    //NSString *fileName = [strArray objectAtIndex:0];
    NSString *fileFormat = [strArray objectAtIndex:1];
    
    if([fileFormat isEqualToString:@"jpg"] == YES) {
        fileFormat = @"jpeg";
    }
        
    NSString *imgType = [NSString stringWithFormat:@"image/%@", fileFormat];
    [request setData:sendData withFileName:dataPath andContentType:imgType forKey:imageKey];//fileName
    
    if(syncMode == SYNCHRONOUS) {
        [request startSynchronous];
    }
    else {
        [request setCompletionBlock:^{
            // Use when fetching text data
            //NSString *responseString = [request responseString];
            
            // Use when fetching binary data
            //NSData *responseData = [request responseData];
        }];
        [request setFailedBlock:^{
            //NSError *error = [request error];
        }];
        
        [request startAsynchronous];
    }
    
    NSString *response = [request responseString];
    NSError *error = [request error];
    
    if(!error && ([response isEqualToString:@"\"FAILED\""] == NO))
    {
        
        return response;
    }
    else 
    {
        return @"FAILED";
    }

}

/* Account Module */
+(BOOL)requestLoginWithEmail:(NSString *)email password:(NSString *)password retData:(NSMutableDictionary **)retJSON
{
#ifdef TESTING_MODE
    *retJSON = [NSDictionary dictionaryWithObject:@"kwang" forKey:@"uid"];
    return YES;
#else
    NSString *queryString = [NSString stringWithFormat:LOGIN_QUERY_STRING, email, password];
    
    NSString *retStr = [self generalRequest:GET syncMode:SYNCHRONOUS apiName:@"account/login" sendData:queryString];
    if([retStr isEqualToString:@"FAILED"] == NO)
    {
        NSError *error;
        NSData *jsonData = [retStr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:(NSData *)jsonData error:(NSError **)&error];
        
        *retJSON = [[dictionary mutableCopy] autorelease];
        
        return YES;
    }
    else 
    {
        return NO;
    }
    
#endif
}


+(BOOL)requestRegisterWithEmail:(NSString *)email password:(NSString *)password firstName:(NSString *)firstName lastName:(NSString *)lastName phone:(NSString *)phone retData:(NSMutableDictionary **)retJSON
{
#ifdef TESTING_MODE
    *retJSON = [NSDictionary dictionaryWithObject:@"kwang" forKey:@"uid"];
    return YES;
#else
    //generate JSON string
    NSString *jsonString = [NSString stringWithFormat:REGISTRATION_JSON_STRING, 
                            email, password, firstName, lastName, phone];
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString *retStr = [CarpoolWithFriendsAdapter generalRequest:POST syncMode:SYNCHRONOUS apiName:@"account/register" sendData:jsonData];
    if([retStr isEqualToString:@"FAILED"] == NO)
    {
        NSError *error;
        NSData *jsonData = [retStr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:(NSData *)jsonData error:(NSError **)&error];
        
        *retJSON = [[dictionary mutableCopy] autorelease];
        return YES;
    }
    else 
    {
        return NO;
    }
#endif
}

+(BOOL)requestProfileWithUserId:(NSString*)userId retData:(NSMutableDictionary**)retJSON
{
    NSString *jsonString = [NSString stringWithFormat:PROFILE_SEARCH_QUERY_STRING, 
                            userId];
    
    NSString *retStr = [CarpoolWithFriendsAdapter generalRequest:GET syncMode:SYNCHRONOUS apiName:PROFILE_SEARCH_API
                                                        sendData:jsonString];
    if([retStr isEqualToString:@"FAILED"] == NO)
    {
        NSError *error;
        NSData *jsonData = [retStr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:(NSData *)jsonData error:(NSError **)&error];
        
        *retJSON = [[dictionary mutableCopy] autorelease];
        return YES;
    }
    else 
    {
        return NO;
    }
}

+(BOOL)requestUpdateProfileWithUserId:(NSString*)userId field:(NSDictionary*)fields retData:(NSMutableDictionary**)retJSON
{
    NSString *jsonString = [NSString stringWithFormat:PROFILE_UPDATE_JSON_STRING, 
                            userId];
    //iterate dictionary
    for(id key in fields){
        jsonString = [NSString stringWithFormat:@"%@,\"%@\":\"%@\"", jsonString, (NSString*)key, [fields objectForKey:key]];
            
    }
    jsonString = [NSString stringWithFormat:@"{%@}", jsonString];
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString *retStr = [CarpoolWithFriendsAdapter generalRequest:PUT syncMode:SYNCHRONOUS apiName:PROFILE_UPDATE_API
                                                        sendData:jsonData];
    if([retStr isEqualToString:@"FAILED"] == NO)
    {
        NSError *error;
        NSData *jsonData = [retStr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:(NSData *)jsonData error:(NSError **)&error];
        
        *retJSON = [[dictionary mutableCopy] autorelease];
        return YES;
    }
    else 
    {
        return NO;
    }
}

+(BOOL)requestUpdateProfileImageWithUserId:(NSString*)userId photo:(NSString*)image retData:(NSMutableDictionary**)retJSON
{
    UIImage *uiImage=[UIImage imageNamed:image];
    NSData *imageData = UIImageJPEGRepresentation(uiImage, 1.0f);
    
    NSString *jsonString = [NSString stringWithFormat:@"{\"uid\":\"%@\"}", userId];
    //NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString *retStr = [CarpoolWithFriendsAdapter formRequest:SYNCHRONOUS apiName:@"account/update_profile_image" dataPath:image sendData:imageData postData:jsonString imageKey:@"profile"];
    
    if([retStr isEqualToString:@"FAILED"] == NO){
        return YES;
    }
    else {
        return NO;
    }
}

/* Stream Module */
+(BOOL)requestPopularStreamWithUserId:(NSString *)userId retData:(NSMutableDictionary **)retJSON
{
    NSError *error;
    NSData *jsonData;
    NSDictionary *dictionary;
#ifdef TESTING_MODE   
    NSString *jsonString = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"popular_stream" ofType:@"json"] encoding:NSUTF8StringEncoding error:(NSError**)&error];
    jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:(NSData*)jsonData error:(NSError**)&error];
    *retJSON = [[dictionary mutableCopy] autorelease];
    return YES;
#else
    // TODO
    
    return NO;
#endif
}

+(BOOL)requestAllFriendsStreamWithUserId:(NSString *)userId retData:(NSMutableDictionary **)retJSON
{
    NSError *error;
    NSData *jsonData;
    NSDictionary *dictionary;
#ifdef TESTING_MODE   
    NSString *jsonString = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"friends_stream" ofType:@"json"] encoding:NSUTF8StringEncoding error:(NSError**)&error];
    jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:(NSData*)jsonData error:(NSError**)&error];
    *retJSON = [[dictionary mutableCopy] autorelease];
    return YES;
#else
    // TODO
    
    return NO;
#endif
}

+(BOOL)requestStreamWithUserId:(NSString *)userId retData:(NSMutableDictionary **)retJSON
{
    NSError *error;
    NSData *jsonData;
    NSDictionary *dictionary;
#ifdef TESTING_MODE   
    NSString *jsonString = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"my_stream" ofType:@"json"] encoding:NSUTF8StringEncoding error:(NSError**)&error];
    jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:(NSData*)jsonData error:(NSError**)&error];
    *retJSON = [[dictionary mutableCopy] autorelease];
    return YES;
#else
    // TODO
    
    return NO;
#endif
}



//-(void)requestFinished:(ASIHTTPRequest*)request
//{
//    //Use when fetching text data
////    NSString *responseString = [request responseString];
//    
//    //Use when fetching binary data
//    //NSData *responseData =[request responseData];
//    
//}
//
//-(void)requestFailed:(ASIHTTPRequest*)request
//{
////    NSError *error = [request error];
//}
@end
